<template>
  <el-dialog title="脚本编辑" :visible.sync="visible" width="90%" :before-close="handleClose">
    <editor v-model="resourceEditArea" :lang="lang" theme="chrome" width="100%" height="400px" @init="editorInit" />
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="confirmResourceEdit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { detail, updateContent } from '@/api/perf/script.js'
export default {
  components: {
    editor: require('vue2-ace-editor')
  },
  data() {
    return {
      visible: false,
      lang: 'xml',
      id: '',
      resourceEditArea: 'resourceEditArea', // taexarea内容
      updateResourceBody: {} // 编辑脚本的消息体
    }
  },
  methods: {
    init(id) {
      this.visible = true
      this.id = id
      this.viewResourceEdit()
    },
    editorInit() {
      require('brace/ext/language_tools') // language extension prerequsite...
      require('brace/theme/chrome')
      // language
      require('brace/mode/xml')
      require('brace/mode/javascript')
      require('brace/mode/less')
      require('brace/mode/java')
      require('brace/mode/scala')
      require('brace/mode/html')
      // snippet
      require('brace/snippets/xml')
      require('brace/snippets/javascript')
      require('brace/snippets/less')
      require('brace/snippets/java')
      require('brace/snippets/scala')
      require('brace/snippets/html')
    },
    // 编辑脚本
    viewResourceEdit() {
      this.updateResourceBody.id = this.id
      this.updateResourceBody.operator = '前端todo'
      detail(this.id).then(respnose => {
        if (respnose && respnose.code === 200) {
          const { data } = respnose
          this.lang = data.format
          this.resourceEditArea = data.content
        } else {
          this.resourceEditArea = '查询出现异常：' + respnose.message
        }
      })
    },
    // 确认编辑脚本
    confirmResourceEdit() {
      this.updateResourceBody.content = this.resourceEditArea
      updateContent(this.updateResourceBody).then(respnose => {
        if (respnose && respnose.code === 200) {
          this.$message.success(respnose.data)
          this.visible = false
        } else {
          this.$message.error(respnose.message)
        }
      })
    },
    // 模态框关闭判断
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    }
  }
}
</script>

<style>
</style>
